package br.edu.ufcg.dsc.services;

import java.util.List;

import javax.persistence.EntityTransaction;

import br.edu.ufcg.dsc.domain.Unit;

public class UnitService extends BaseService {

	public static Unit find(String id) {
		return entity.find(Unit.class, id);
	}
	
	public static void persist(Unit u) {
		EntityTransaction tx = entity.getTransaction();

		tx.begin();
		try {
			if (find(u.getId()) == null)
				entity.persist(u);
			else
				entity.merge(u);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<Unit> findUnitsByResource(int id) {
		return (List<Unit>) entity.createQuery
			("SELECT u FROM br.edu.ufcg.dsc.domain.Unit u WHERE u.resource.id = :id")
				.setParameter("id", id).getResultList();
	}
}
